<template>
  <div class="alarm-manage-container">
    <el-card shadow="hover" class="alarm-card">
      <template #header>
        <div class="header-container">
          <h3>告警管理</h3>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="refreshAlarms">刷新数据</el-button>
          </div>
        </div>
      </template>

      <div class="filter-container">
        <el-form :inline="true" :model="filterForm">
          <el-form-item label="告警级别">
            <el-select v-model="filterForm.level" placeholder="请选择告警级别" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="低" value="low"></el-option>
              <el-option label="中" value="medium"></el-option>
              <el-option label="高" value="high"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态">
            <el-select v-model="filterForm.status" placeholder="请选择处理状态" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="待处理" value="pending"></el-option>
              <el-option label="已处理" value="processed"></el-option>
              <el-option label="已忽略" value="ignored"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="alarmList" border stripe style="width: 100%">
        <el-table-column prop="alarmId" label="告警ID" width="120" />
        <el-table-column prop="deviceName" label="设备名称" width="150" />
        <el-table-column prop="alarmType" label="告警类型" width="120" />
        <el-table-column prop="alarmTime" label="告警时间" width="180" />
        <el-table-column prop="alarmLevel" label="告警级别" width="100">
          <template #default="scope">
            <el-tag :type="getAlarmLevelType(scope.row.alarmLevel)">
              {{ getAlarmLevelText(scope.row.alarmLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="处理状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleProcess(scope.row)" v-if="scope.row.status === 'pending'">处理</el-button>
            <el-button size="small" type="info" @click="handleIgnore(scope.row)" v-if="scope.row.status === 'pending'">忽略</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 处理告警对话框 -->
    <el-dialog v-model="processDialogVisible" title="处理告警" width="500px" append-to-body>
      <el-form :model="processForm" label-width="100px">
        <el-form-item label="告警ID">
          <el-input v-model="processForm.alarmId" disabled></el-input>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="processForm.deviceName" disabled></el-input>
        </el-form-item>
        <el-form-item label="告警类型">
          <el-input v-model="processForm.alarmType" disabled></el-input>
        </el-form-item>
        <el-form-item label="处理意见">
          <el-input v-model="processForm.processRecord" type="textarea" rows="4" placeholder="请输入处理意见"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAlarms, processAlarm, ignoreAlarm, deleteAlarm } from '../../api/alarm';
import { updateAlarmStats } from '../../api/dashboard';

export default {
  name: 'AlarmManageView',
  setup() {    const isMobile = ref(window.innerWidth < 768);
    const handleResize = () => {
      isMobile.value = window.innerWidth < 768;
    };

    // 获取告警级别对应的类型
    const getAlarmLevelType = (level) => {
      switch (level) {
        case 'high':
          return 'danger';
        case 'medium':
          return 'warning';
        case 'low':
          return 'info';
        default:
          return 'info';
      }
    };

    // 获取告警级别对应的文本
    const getAlarmLevelText = (level) => {
      switch (level) {
        case 'high':
          return '高';
        case 'medium':
          return '中';
        case 'low':
          return '低';
        default:
          return '未知';
      }
    };

    // 获取处理状态对应的类型
    const getStatusType = (status) => {
      switch (status) {
        case 'pending':
          return 'danger';
        case 'processed':
          return 'success';
        case 'ignored':
          return 'info';
        default:
          return 'info';
      }
    };

    // 获取处理状态对应的文本
    const getStatusText = (status) => {
      switch (status) {
        case 'pending':
          return '待处理';
        case 'processed':
          return '已处理';
        case 'ignored':
          return '已忽略';
        default:
          return '未知';
      }
    };    // 刷新告警列表
    const refreshAlarms = async () => {
      await fetchAlarms();
      ElMessage.success('告警数据已刷新');
      // 确保更新仪表盘的告警统计数据
      await updateAlarmStats();
    };

    onMounted(() => {
      window.addEventListener('resize', handleResize);
      fetchAlarms();
    });

    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize);
    });

    const filterForm = reactive({
      level: '',
      status: '',
      timeRange: []
    });

    const loading = ref(false);
    const alarmList = ref([]);
    const total = ref(0);
    const pageSize = ref(10);
    const currentPage = ref(1);    const fetchAlarms = async () => {
      loading.value = true;
      try {
        const params = {
          _page: currentPage.value,
          _limit: pageSize.value,
          alarmLevel: filterForm.level || undefined,
          status: filterForm.status || undefined,
          startDate: filterForm.timeRange[0] || undefined,
          endDate: filterForm.timeRange[1] || undefined
        };

        const response = await getAlarms(params);
        total.value = parseInt(response.headers['x-total-count'] || '0');
        alarmList.value = response.data;
        
        // 在数据更新后，同步更新仪表盘数据
        await updateAlarmStats();
      } catch (error) {
        ElMessage.error('获取告警数据失败');
      } finally {
        loading.value = false;
      }
    };

    const handleFilter = () => {
      currentPage.value = 1;
      fetchAlarms();
    };

    const resetFilter = () => {
      filterForm.level = '';
      filterForm.status = '';
      filterForm.timeRange = [];
      handleFilter();
    };

    const handleSizeChange = (size) => {
      pageSize.value = size;
      fetchAlarms();
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      fetchAlarms();
    };

    const processDialogVisible = ref(false);
    const processForm = reactive({
      alarmId: '',
      deviceName: '',
      alarmType: '',
      processRecord: ''
    });

    const handleProcess = (row) => {
      processForm.alarmId = row.alarmId;
      processForm.deviceName = row.deviceName;
      processForm.alarmType = row.alarmType;
      processDialogVisible.value = true;
    };    const submitProcess = async () => {
      try {
        await processAlarm(processForm);
        ElMessage.success('告警处理成功');
        processDialogVisible.value = false;
        fetchAlarms();
        // 更新仪表盘告警统计数据
        await updateAlarmStats();
      } catch (error) {
        ElMessage.error('告警处理失败');
      }
    };

    const handleIgnore = async (row) => {
      try {
        await ignoreAlarm(row.alarmId);
        ElMessage.success('告警已忽略');
        fetchAlarms();
        // 更新仪表盘告警统计数据
        await updateAlarmStats();
      } catch (error) {
        ElMessage.error('忽略告警失败');
      }
    };

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该告警吗？', '提示', {
          type: 'warning'
        });
        await deleteAlarm(row.alarmId);
        ElMessage.success('告警删除成功');
        fetchAlarms();
        // 更新仪表盘告警统计数据
        await updateAlarmStats();
      } catch (error) {
        ElMessage.error('删除告警失败');
      }
    };return {
      isMobile,
      filterForm,
      loading,
      alarmList,
      total,
      pageSize,
      currentPage,
      processDialogVisible,
      processForm,
      fetchAlarms,
      refreshAlarms,
      handleFilter,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleProcess,
      submitProcess,
      handleIgnore,
      handleDelete,
      getAlarmLevelType,
      getAlarmLevelText,
      getStatusType,
      getStatusText
    };
  }
};
</script>

<style scoped>
.alarm-manage-container {
  padding: 20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
